import * as bm from "/js/baseModule.js";

require('/js/collapse.js');

export class Module extends bm.baseModule {
    constructor(view) {
        super(view);
        let that = this;
        this.proInfo = {};
        this.int1 = '';
        this.int2 = '';
        this.int3 = '';
        this.pointAtLeast = '';
        this.scope = this;
        this.isBomb = false;
        this.TOTAL_GRAB_NUMBER = 1;

        // 如果id不存在
        if (globalData.current_demand.id == '') {
            // 如果浏览器链接有did参数，则刷新
            if (funs.qs('did')) {
                window.location.reload();
            } else {
                location.hash = 'index';
            }
        }
        //详情页渲染
        let v_details = this.find('.DemandInfo_vue')[0];
        let data = globalData;
        this.proInfo = new Vue({
            el: v_details,
            data: data,
            methods: {
                updateTime: function (startTime) {
                    startTime = startTime + '';
                    let text;
                    let stime = startTime * 1000;
                    let date = new Date().getTime();
                    let gapMin = Math.floor((date - stime) / 1000 / 60);
                    if (gapMin <= 0) {
                        //防止偶尔出现的js取时间不准确
                        gapMin = 1;
                    }
                    let gapHour = Math.floor((date - stime) / 1000 / 60 / 60);

                    if (gapHour <= 24) {
                        text = gapHour + '小时前';
                        if (gapMin < 60) {
                            text = gapMin + '分钟前';
                        }
                    } else if (gapHour <= 24 * 8) {
                        gapHour = Math.floor(gapHour / 24);
                        text = gapHour + '天前'
                    } else if (gapHour > 24 * 8) {
                        let ddd = new Date(startTime * 1000);
                        gapHour = (ddd.getMonth() + 1) + '-' + ddd.getDate();
                        text = gapHour
                    } else {
                        //防止意外情况，暂时如此处理
                        text = '刚刚'
                    }
                    return text;
                },
                /*搜索词*/
                sem: function (str) {
                    if (str) {
                        str = str.replace(/\'/g, '"');
                        let sem = JSON.parse(str);
                        return sem.word;
                    } else {
                        return "";
                    }
                },
            },
            computed:{
                //第N次发布理由列表处理
                publish_remark_list: function () {
                    let count = this.current_demand.published_count;
                    let remark = JSON.parse(this.current_demand.publish_remark);
                    let list = new Array();
                    let aaa;
                    if (!remark) {
                        return
                    }
                    for (let i = 1; i <= count; i++) {
                        if (remark[i + '']) {
                            aaa = { 'inedx': i, 'val': remark[i + ''] };
                            list.push(aaa);
                        }
                    }
                    return list.reverse();
                }
            }
        });

        /**
         * 如果是直接进入当前页面，则先loading一会儿，等数据回来
         */
        if (globalData.entryPage == 'DemandDetail') {
            this.find('.sendImgPending').removeClass('hide');
            let id = globalData.current_demand.id;
            api.getDemandInfo({ "id": id }, {
                succ: function (demand) {
                    $.extend(true, globalData.current_demand, demand);
                    that.find('.sendImgPending').addClass('hide');
                    that._init();
                },
                fail: function (json) {
                    //  如果是项目已被删除或者不存在
                    if (json.status = "41004002") {
                        funs.openModal('modules/modals/CommonModal.JS', function (mod) {
                            mod.setType(9);
                        })
                    } else {
                        funs.tip(json.msg, '', 'fail');
                        setTimeout(function () {
                            that._evt_goback();
                        }, 2000)
                    }
                }
            });
        }
        //监听数据返回
        $(document).on('data_update', function () {
            // 如果是直接进入当前页面，且项目已被删除或者不存在，则回到项目大厅
            if (globalData.entryPage == 'DemandDetail' && globalData.current_demand.uid == '0000X') {
                //订单不可见
                funs.openModal('modules/modals/CommonModal.JS', function (mod) {
                    mod.setType(9);
                })
            }

            //铜牌一口价的订单
            if (globalData.current_demand.status == '8') {
                if (globalData.user.level != '20') {
                    //不是铜牌
                    //订单不可见
                    funs.openModal('modules/modals/CommonModal.JS', function (mod) {
                        mod.setType(9);
                    })
                } else {
                    //是铜牌
                    if (globalData.pack.bronze_medal_odd_days <= 0) {
                        //铜牌套餐过期
                        //订单不可见
                        funs.openModal('modules/modals/CommonModal.JS', function (mod) {
                            mod.setType(9);
                        })
                    }
                }
            }

        });

        /** 折叠 */
        $('.collapse').collapse();
        $('.panel-collapse').on('show.bs.collapse', function () {
            // 展开执行一些动作...
            let panelCollapse = $(this);
            panelCollapse.parent().find('.icon-circle-down').addClass('rotate');
            panelCollapse.parent().find('.panel-heading').css('padding-bottom', '0');

        }).on('hide.bs.collapse', function () {
            // 折叠执行一些动作...
            let panelCollapse = $(this);
            panelCollapse.parent().find('.icon-circle-down').removeClass('rotate');
            panelCollapse.parent().find('.panel-heading').css('padding-bottom', '0.1rem');
        }).on('shown.bs.collapse', function () {
            // 执行一些动作...
            $('#DemandDetail').scrollTop($('#DemandDetail')[0].scrollHeight);
        });

        //项目浏览数+1
        api.demandAddScan({ "id": parseInt(globalData.current_demand.id) }, {
            succ: function () {
                console.log('项目浏览量+1');
                globalData.current_demand.scan_count += 1;
            }
        });

    }

    _init() {
        let that = this;
        //汇币的计算
        this.countOfferPoint();

        /** 定时任务：定时请求项目参与表，并更新相关数据 */
        let demand = globalData.current_demand;
        // 进行中的不为采购的真实项目，才会更新数据
        if (demand.tag == 0 && demand.cate != '4' && (demand.status == '8' || demand.status == '10' || demand.status == '11' || demand.status == '15' || demand.status == '20' || demand.status == '30')) {
            // 获取项目参与列表,更新参与表和项目状态
            window.clearInterval(this.int2);
            this.int2 = setInterval(function () {
                api.getParticInfo({ demand_id: globalData.current_demand.id }, {
                    succ: function (json) {
                        let list = json.partic_supplier_list;
                        let isSame = true;
                        let a = JSON.stringify(globalData.current_demand.supplier_list);
                        let b = JSON.stringify(list);
                        a = a.replace(/\"info\":\"[\u4e00-\u9fa5]{3,6}\"/g, '').replace(/\"succ\_item\":[a-z]{4,5}/g, '');
                        b = b.replace(/\"info\":\"[\u4e00-\u9fa5]{3,6}\"/g, '').replace(/\"succ\_item\":[a-z]{4,5}/g, '');
                        if (a != b) isSame = false;
                        globalData.current_demand.supplier_list.length = 0;
                        globalData.current_demand.supplier_list.push(...list);
                        globalData.current_demand.status = json.demand_status;
                        globalData.current_demand.has_max = json.has_max;
                        //找到自己的信息并更新项目参与状态
                        $.each(list, function (index, value) {
                            if (value.id == globalData.user.user_id) {
                                globalData.current_demand.supplier_partic_status = value.status;
                            }
                        });
                        let bronze_partic_info = json.bronze_partic_info;
                        //铜牌一口价下成功信息
                        $.extend(true, globalData.current_demand.bronze_partic_info, bronze_partic_info);
                        //如果在一阶段，监控到有新报价，则更新现有报价
                        if (!isSame && json.demand_status == '10') {
                            that.countOfferPoint();
                        }
                    }
                });
            }, 2000);
        }
    }

    //页面加载事件
    afterInstall() {
        let that = this;
        $('.panel-collapse').collapse('hide');
        if (globalData.entryPage != 'DemandDetail') {
            this._init();
        }
        if (globalData.entryPage == 'DemandDetail') {
            api.getUserInfo({
                succ: function (user) {
                    $.extend(globalData.user, user);
                    globalData.pack.uid = user.user_id;
                    funs.removeWelcome();
                    that.grabCount();
                }
            });
        }
        // 无论啥类型项目，都要去取参与列表
        api.getParticInfo({ demand_id: globalData.current_demand.id }, {
            succ: function (json) {
                let list = json.partic_supplier_list;
                let bronze_partic_info = json.bronze_partic_info;
                //铜牌一口价下成功信息
                $.extend(true, globalData.current_demand.bronze_partic_info, bronze_partic_info);
                globalData.current_demand.supplier_list.length = 0;
                globalData.current_demand.supplier_list.push(...list);
                globalData.current_demand.status = json.demand_status;
                var flag = true;
                //找到自己的信息并更新项目参与状态
                $.each(list, function (index, value) {
                    if (value.id == globalData.user.user_id) {
                        globalData.current_demand.supplier_partic_status = value.status;
                    }

                    // 如果项目已经完成，并有人抢单成功了
                    if(parseInt(json.demand_status)>30 && flag){
                        if(parseInt(value.status)>10){
                            funs.openModal('modules/modals/CommonModal.js', function (mod) {
                                mod.setType(23,{name:value.nick,phone:value.mobile});
                            });
                            window.clearInterval(this.int2);
                            flag = false;
                        }
                    }
                });

                //抢单倒计时
                that.grabCount();
                that.countOfferPoint();
            }
        });

    }

    /*==============录音音频处理-start=============*/

    //录音播放暂停
    _evt_playPause(target) {
        if (globalData.current_demand.supplier_partic_status != '200' && globalData.current_demand.audio_sensitive) {
            //audio_sensitive==true 敏感录音
            //未参与并且是敏感录音，弹一个提示气泡
            funs.openModal('modules/modals/CommonModal.JS', function (mod) {
                mod.setType(7);
            });
            return;
        }

        let that = this;
        if (globalData.current_demand.tag != 0) {
            //虚拟订单不可播放
            return;
        }
        //如果录音加载失败
        let audioTime = this.find('.audio-time');
        let audio = document.getElementById("audioTag");
        if (audio.paused) {
            audio.play();
            this.find('.audio-time').removeClass('hide');
            this.find('.txt').addClass('hide');
            //改变icon
            $(target).find('.play-pause>span').removeClass('icon-play-one').addClass('icon-pause-one')
        } else {
            audio.pause();
            $(target).find('.play-pause>span').removeClass('icon-pause-one').addClass('icon-play-one')
        }

        //监听音频播放时间并更新进度条
        audio.addEventListener('timeupdate', function () {
            //更新进度条
            let audio = document.getElementsByTagName('audio')[0];
            // $('.audio-time').html(that.transTime(audio.duration - audio.currentTime));
            let rate = parseInt(audio.currentTime / audio.duration * 100 * 3.6);
            if (rate <= 180) {
                $('.circle_right').css('transform', 'rotate(' + rate + 'deg)');
            } else {
                $('.circle_right').css({
                    'transform': 'rotate(0deg)',
                    "background": "#f8d498"
                });
                $('.circle_left').css('transform', 'rotate(' + (rate - 180) + 'deg)');
            }
        }, false);
        //监听播放完成事件
        audio.addEventListener('ended', function () {
            //播放完成
            let audio = document.getElementsByTagName('audio')[0];
            audio.currentTime = 0;
            audio.pause();
            that.find('.play-pause>span').removeClass('icon-pause-one').addClass('icon-play-one');
            that.find('.audio-time').addClass('hide');
            that.find('.txt').removeClass('hide');
            $('.circle_right').css({
                'transform': 'rotate(0deg)',
                "background": "#FFECCD"
            });
            $('.circle_left').css('transform', 'rotate(0deg)');
        }, false);
    };

    //转换音频时长格式
    transTime(time) {
        let duration = parseInt(time);
        let minute = Math.floor(duration / 60);
        let sec = duration % 60 + '';
        let isM0 = ':';
        if (minute == 0) {
            minute = '00';
        } else if (minute < 10) {
            minute = '0' + minute;
        }
        if (sec.length == 1) {
            sec = '0' + sec;
        }
        return minute + isM0 + sec
    }

    /*==============录音音频处理-end=============*/

    //点击查看大图
    _evt_scanBig(obj) {
        let src = $(obj).attr('src');
        let width = $(obj).width();
        let height = $(obj).height();
        let rate = width / height;//宽高比
        let hh = $(window).width();//大图的宽 == 屏幕宽度
        let bgh = hh / rate / 2;  // 计算出大图的高度 de 一半

        //dom插入
        let bigImg = '<div class="bigImgBg" evt="closeBigImg"><img class="bigImg" src="' + src + '"/></div>';
        $(this.view).append(bigImg);

        //让图片垂直居中
        $('.bigImg').css('margin-top', -bgh + 'px');
    };

    _evt_closeBigImg(obj) {
        $(obj).remove();
    };

    /*拨打电话方法*/
    _evt_fromWPH() {
        funs.openModal('modules/modals/CommonModal.js', function (mod) {
            mod.setType(6, { phone: globalData.current_demand.user.phone })
        })
    }


    // 页面卸载事件
    afterUninstall() {
        let that = this;
        // 如果录音存在，离开洽谈室时重置录音播放；
        if (globalData.current_demand.audio) {
            //播放完成
            let audio = document.getElementsByTagName('audio')[0];
            audio.currentTime = 0;
            audio.pause();
            this.find('.play-pause>span').removeClass('icon-pause-one').addClass('icon-play-one');
            this.find('.audio-time').addClass('hide');
            this.find('.txt').removeClass('hide');
        }
        //倒计时清空
        window.clearInterval(that.int1);
        window.clearInterval(that.int2);
        this.find('.count-deadline').text('');
        globalData.currPage = 'index';
    }

    //计算竞价起拍价格
    countOfferPoint() {
        let demand = globalData.current_demand;
        let list = demand.supplier_list;
        let start_point = demand.bid_start_point;
        let realPoint;
        //首轮竞价
        if (demand.status == '10') {

            // 如果参与过
            if (demand.supplier_partic_status != '0') {
                if (demand.my_offer >= 200) {
                    demand.self_has_max = true;
                } else {
                    demand.self_has_max = false;
                }
                realPoint = demand.my_offer;
            } else {
                realPoint = start_point;
            }

        }
        //已经抢单结束或项目结束
        if (parseInt(demand.status) >= 100) {
            realPoint = start_point;
        }
        // 二次竞价中
        if (demand.status == '20') {
            realPoint = demand.price;
        }
        //免费竞价状态
        if (demand.status == '30') {
            realPoint = '0';
        }
        if (realPoint >= 200) {
            realPoint = 200;
        }
        this.pointAtLeast = realPoint;
        if ($('.new-offer-input').val() && (parseInt($('.new-offer-input').val().trim()) >= realPoint)) { return; }
        $('.new-offer-input').val(realPoint);
        demand.curr_offer = realPoint;

    }


    //竞价项目倒计时
    grabCount() {
        let demand = globalData.current_demand;
        if (demand.cate == '4') return;
        let dl;
        // 进行中的项目或铜牌一口价，取项目的发布时间
        if (demand.status == '10' || demand.status == '8') {
            dl = demand.published_at;
            if (!dl) return;
            dl = dl * 1000;
            window.clearInterval(this.int1);
            this.int1 = setInterval(() => {
                let now = new Date().getTime();
                let m, s;
                //获得跟当前时间的间隔秒数
                let gapSec = Math.floor((now - dl) / 1000);
                //如果超过5分钟
                if (gapSec > 60 * 5) {
                    window.clearInterval(this.int1);
                    $('.deadline').hide();
                    return
                }
                gapSec = 60 * 5 - gapSec;
                m = parseInt(gapSec / 60);
                if (m > 0) {
                    s = gapSec - 60 * m;
                } else {
                    s = gapSec;
                }
                if (m < 10) m = '0' + m;
                if (s < 10) s = '0' + s;

                let text = '00:' + m + ':' + s;
                $('.deadline').show();
                this.find('.count-deadline').text(text);
            }, 1000);
            //竞价成功的项目，取竞价成功的时间
        } else if (demand.supplier_partic_status == '110' || demand.supplier_partic_status == '120') {
            let list = demand.supplier_list;
            $.each(list, function (index, value) {
                if (value.id == globalData.user.user_id) {
                    dl = value.bid_win_at;
                }
            })
            if (!dl) return;
            dl = dl * 1000;
            window.clearInterval(this.int3);
            this.int3 = setInterval(() => {
                let now = new Date().getTime();
                let m, s;
                //获得跟当前时间的间隔秒数
                let gapSec = Math.floor((now - dl) / 1000);
                //如果超过5分钟
                if (gapSec > 60 * 5) {
                    window.clearInterval(this.int3);
                    $('.deadline').hide();
                    return
                }
                gapSec = 60 * 5 - gapSec;
                m = parseInt(gapSec / 60);
                if (m > 0) {
                    s = gapSec - 60 * m;
                } else {
                    s = gapSec;
                }
                if (m < 10) m = '0' + m;
                if (s < 10) s = '0' + s;

                let text = '00:' + m + ':' + s;
                $('.deadline').show();
                this.find('.count-deadline').text(text);
            }, 1000);
            // $('.deadline').hide();
        }

    }

    /** 点击竞价规则滚动到页面底部 */
    _evt_scrollToRules() {
        $('#collapseFour').collapse('show');
        $('#DemandDetail').animate({ scrollTop: $('#DemandDetail')[0].scrollHeight }, 600);
    }


    _evt_goIndex() {
        location.hash = 'index';
    }


    _evt_loadRefunds() {
        location.hash = 'project/demand/Refunds';
    }

    _evt_loadValueAddService() {
        location.hash = 'pack/MyPack';
    }

    _evt_goFollowWx(){
        location.hash = 'project/FollowWx';
    }

    _evt_modalFollowWx(){
        // 事件记录
        api.collectUserMove({"btn_type":2});
        funs.openModal('modules/modals/CommonModal.js', function (mod) {
            mod.setType(22);
        })
    }
}
